import lrc from './data.js'

var doms = {
  lyriceUl: document.querySelector('.lyrics-list-content'),
  audio: document.querySelector('audio')
}

var lyricsArr = []
// var

initLrc()
renderLyrics()
OnUpdateAudioLyrics()

doms.audio.addEventListener('timeupdate', OnUpdateAudioLyrics)
function OnUpdateAudioLyrics() {
  var index = getCurrentLrcIndex()
  var marginTop = (6 - index) * 32
  doms.lyriceUl.style.marginTop = marginTop + 'px'

  doms.lyriceUl.querySelectorAll('.lrc-active').forEach((item) => {
    item.classList.remove('lrc-active')
  })

  var li = doms.lyriceUl.children[index]
  if (!li) return
  li.classList.add('lrc-active')
}

window.getCurrentLrcIndex = getCurrentLrcIndex
function getCurrentLrcIndex() {
  var currentTime = doms.audio.currentTime
  for (var i = 0; i < lyricsArr.length; i++) {
    if (currentTime < lyricsArr[i].time) {
      return i - 1
    }
  }
  return lyricsArr.length - 1
}

function renderLyrics() {
  var domFrag = document.createDocumentFragment()
  lyricsArr.forEach((lyric) => {
    var li = document.createElement('li')
    li.classList.add('text-base/8')
    li.textContent = lyric.text
    domFrag.appendChild(li)
  })
  doms.lyriceUl.appendChild(domFrag)
}

function initLrc() {
  var lrcArr = lrc.split('\n')

  lrcArr.forEach((lrc) => {
    var time = lrc.substring(1, 9)

    var lrcObj = {
      time: convertTime(time),
      text: lrc.split(']')[1]
    }
    lyricsArr.push(lrcObj)
  })
}

function convertTime(time) {
  var timeArr = time.split(':')
  var time = +parseInt(timeArr[0]) * 60 + +parseFloat(timeArr[1])
  return time
}
